package com.icesoft.system.safe.filter;

import com.icesoft.system.safe.config.SafeHttpServletRequest;
import com.icesoft.system.safe.helper.RequestHelper;
import com.icesoft.system.safe.service.SafeRequestCryptoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(urlPatterns = "/*", filterName = "safeRequestFilter")
public class SafeRequestFilter implements Filter {

	private final SafeRequestCryptoService safeRequestCryptoService;

	public SafeRequestFilter(SafeRequestCryptoService safeRequestCryptoService) {
		this.safeRequestCryptoService = safeRequestCryptoService;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		if (log.isTraceEnabled() || (log.isDebugEnabled() && "true".equals(request.getHeader("logRequest")))) {
			Enumeration<String> headers = request.getHeaderNames();
			StringBuilder sb = new StringBuilder("remote ip:" + RequestHelper.getRemoteIP(request)).append("\n");
			sb.append("请求 url: " + request.getRequestURI()).append("\n");
			sb.append("----------request headers---------- \n");
			while (headers.hasMoreElements()) {
				String name = headers.nextElement();
				String val = request.getHeader(name);
				sb.append(name).append(" = ").append(val).append("\n");
			}
			sb.append("----------request params---------- \n");
			RequestHelper.getRequestParamMap(request).forEach((key, val) -> {
				sb.append(key).append(" = ").append(val).append("\n");
			});
			sb.append("正式环境请不要添加该请求头logRequest，否则将导致日志文件过大");
			if (log.isTraceEnabled()) {
				log.trace(sb.toString());
			} else {
				log.debug(sb.toString());
			}
		}
		SafeHttpServletRequest safeHttpServletRequest = new SafeHttpServletRequest(safeRequestCryptoService, request);
		chain.doFilter(safeHttpServletRequest, response);
	}
}
